﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace SerialManager
{
    /// <summary>
    /// Trida zaobalujici informace o cislu sezony a epizody
    /// </summary>
    public class EpisodeInfo
    {
        /// <summary>
        /// Cislo sezony
        /// </summary>
        public int Season { get; set; }
        
        /// <summary>
        /// Cislo epizody
        /// </summary>
        public int Number { get; set; }

        /// <summary>
        /// Nazev epizody
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// Pole obsahujici dalsi pripadne shody, kdy je v nazvu zapsana epizoda vice zpusoby
        /// a nelze tedy jednoznacne urcit urceni epizody
        /// </summary>
        public EpisodeInfo[] OtherMatches { get; private set; }

        /// <summary>
        /// Vyhledavani informaci o sezone a cisle epizody v nazvu souboru
        /// </summary>
        /// <param name="file">Soubor ke zpracovani</param>
        /// <returns>NULL v pripadne zadne shody, jinak vytvorenou instanci tridy</returns>
        public static EpisodeInfo SearchForMatch( FileInfo file )
        {
            var matches = (
                from exp in Core.EpisodeNumbers
                let match = exp.Match( file.Name )
                where match.Success
                select new EpisodeInfo
                {
                    Season = Convert.ToInt32( match.Groups["s"].Value ),
                    Number = Convert.ToInt32( match.Groups["e"].Value )
                }
            );

            if( matches == null || matches.Count() == 0 )
                return null;

            var firstMatch = matches.First();
            if( matches.Count() > 1 )
            {
                firstMatch.OtherMatches = matches
                    .Skip( 1 )
                    .Where( m => m != firstMatch )
                    .ToArray();
            }
            
            return firstMatch;
        }

        /// <summary>
        /// Jednoznacna identifikace epizody
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return (Season * 1000) + Number;
        }

        /// <summary>
        /// Porovnani dvou instanci teto tridy
        /// </summary>
        public override bool Equals( object obj )
        {
            EpisodeInfo ep = obj as EpisodeInfo;
            if( ep == null )
                return false;
            return ( ep.Season == this.Season && ep.Number == this.Number );
        }
    }
}
